package com.kzw.oa.byxt.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.kzw.core.Constants;
import com.kzw.core.mapper.Jackson;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.BeanUtil;
import com.kzw.core.util.ContextUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.util.StringUtil;
import com.kzw.core.web.action.BaseAction;
import com.kzw.oa.byxt.model.CheckMember;
import com.kzw.oa.byxt.model.Subject;
import com.kzw.oa.byxt.model.SubjectOpinion;
import com.kzw.oa.byxt.service.CheckMemberService;
import com.kzw.oa.byxt.service.SubjectOpinionService;
import com.kzw.oa.byxt.service.SubjectService;
import com.kzw.oa.byxt.service.YuXuanService;
import com.kzw.oa.model.system.AppUser;
import com.kzw.oa.service.ext.AppUserService2;
import com.kzw.oa.util.JSON;
import com.kzw.oa.util.JSON2;

@Controller
@Scope("prototype")
public class SubjectAction extends BaseAction {
	@Autowired
	private AppUserService2 appUserService2;
	@Autowired
	private YuXuanService yuXuanService;
	@Autowired
	private SubjectService subjectService;	
	@Autowired
	private CheckMemberService checkMemberService;	
	@Autowired
	private SubjectOpinionService opinionService;
	private Subject subject;
	private Long oid;

	/**
	 * 显示列表
	 */
	public String list() {
		HttpServletRequest request = getRequest();

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
	
		if (ExtjsUtil.isExport(request)) { // 导出报表
			List<Subject> resultList = subjectService.search(filters);
			request.setAttribute("__exportList", resultList);
			return SUCCESS;
		}

		Page<Subject> page = subjectService.search2(pageRequest, filters);

		jsonString = new JSON(page).buildWithFilters(3);
		return SUCCESS;
	}
	
	/**
	 * 教师的题目
	 * */
	public String listMy() {
		HttpServletRequest request = getRequest();

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		
		// 不是超级管理员，则只显示自己的题目
		AppUser currUser = ContextUtil.getCurrentUser();
		if(!currUser.getUserId().equals(AppUser.SUPER_USER)) {
			filters.add(new StringPropertyFilter("EQL_teacher.userId", currUser.getUserId()+""));
		}
	
		if (ExtjsUtil.isExport(request)) { // 导出报表
			List<Subject> resultList = subjectService.search(filters);
			request.setAttribute("__exportList", resultList);
			return SUCCESS;
		}

		Page<Subject> page = subjectService.search2(pageRequest, filters);

		jsonString = new JSON(page).buildWithFilters(3);
		return SUCCESS;
	}
	/**
	 * 教师要审核的题目
	 * */
	public String listMyCheck() {
		HttpServletRequest request = getRequest();

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		
		// 不是超级管理员，则只显示自己的题目
		AppUser currUser = ContextUtil.getCurrentUser();
		if(!currUser.getUserId().equals(AppUser.SUPER_USER)) {
			filters.add(new StringPropertyFilter("EQL_checkMember.member.userId", currUser.getUserId()+""));
		}
	
		if (ExtjsUtil.isExport(request)) { // 导出报表
			List<Subject> resultList = subjectService.search(filters);
			request.setAttribute("__exportList", resultList);
			return SUCCESS;
		}

		Page<Subject> page = subjectService.search2(pageRequest, filters);

		jsonString = new JSON(page).buildWithFilters(5);
		return SUCCESS;
	}

	/**
	 * 教师审核通过的题目
	 * */
	public String listMyTongGuo() {
		HttpServletRequest request = getRequest();

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);

		// 不是超级管理员，则只显示自己的题目
		AppUser currUser = ContextUtil.getCurrentUser();
		if (!currUser.getUserId().equals(AppUser.SUPER_USER)) {
			filters.add(new StringPropertyFilter("EQL_teacher.userId", currUser
					.getUserId() + ""));
			filters.add(new StringPropertyFilter("INI_status", "4,5"));
		}

		if (ExtjsUtil.isExport(request)) { // 导出报表
			List<Subject> resultList = subjectService.search(filters);

			request.setAttribute("__exportList", resultList);
			return SUCCESS;
		}

		Page<Subject> page = subjectService.search2(pageRequest, filters);

		jsonString = new JSON(page).buildWithFilters(3);
		return SUCCESS;
	}
	/**
	 * 选题统计按学生
	 */
	public String listStudent(){

		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(getRequest());
		filters.add(new StringPropertyFilter("EQH_delFlag", Constants.FLAG_UNDELETED+""));
		filters.add(new StringPropertyFilter("GTL_userId", "1"));
		filters.add(new StringPropertyFilter("EQI_roleType", "3"));

		PageRequest pageRequest = ExtjsUtil.getPageReq(getRequest());
		if(pageRequest.getOrderBy() == null) {
			pageRequest.setOrderBy("orgSn,userSn,userId");
			pageRequest.setOrderDir("asc,asc,asc");
		}
		Page<AppUser> page = appUserService2.search2(pageRequest, filters);


		jsonString = new JSON(page).buildWithFilters(3, "appUsers", "userOrgs",
				"department", "orgs", "roles", "authorities", "password",
				"positions", "topModules", "rights", "demension", "company","subject");

		return SUCCESS;
	}
	/**
	 * 最终的选题结果
	 */
	public String listFinal(){

		HttpServletRequest request = getRequest();
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		filters.add(new StringPropertyFilter("EQI_status", "5"));
		if (ExtjsUtil.isExport(request)) { // 导出报表
			List<Subject> resultList = subjectService.search(filters);
			request.setAttribute("__exportList", resultList);
			return SUCCESS;
		}
		Page<Subject> page = subjectService.search2(pageRequest, filters);

		jsonString = new JSON(page).buildWithFilters(3);
		return SUCCESS;
	}
	/**
	 * 批量删除,在删除题目的同时，删除审题老师中有此题的记录
	 * 通过审题老师的id,找到审题者中的审题，并删除之
	 */
	public String multiDel() {
		
		
		String[] ids = getRequest().getParameterValues("ids");
		
		for(String oid : ids) {
			Subject subject = subjectService.get(Long.parseLong(oid));
			CheckMember member = subject.getCheckMember();
			if(member != null) {
				String names = member.getSubjectNames().replaceAll(subject.getName() + "[，,]{0,1}" , "");
				String id = member.getSubjectIds().replaceAll(subject.getOid() + "[，,]{0,1}" , "");
				member.setSubjectNames(names);
				member.setSubjectIds(id);
				checkMemberService.saveOrUpdate(member);
			}
			
		}
		subjectService.remove(ids);
		jsonString = "{success:true}";
		return SUCCESS;
	}

	/**
	 * 显示详细信息
	 * 
	 * @return
	 */
	public String get() {
		Subject subject = subjectService.get(oid);
		setJsonString(new JSON(subject).buildWithFilters(2));
		return SUCCESS;
	}

	/**
	 * 添加及保存操作
	 */
	public String save() {
		subject.setYaoqiu(subject.getYaoqiu().replace("\r", "").replace("\n", "<br>"));
		subject.setSumary(subject.getSumary().replace("\r", "").replace("\n", "<br>"));
		
		if (subject.getOid() == null) {
			subjectService.saveOrUpdate(subject);
			// 保存流程信息
			opinionService.saveOpinion(subject.getOid(), "填写选题申报", true, null);
		} else {
			Subject orgSubject = subjectService.get(subject.getOid());
			try {
				BeanUtil.copyNotNullProperties(orgSubject, subject);
				subjectService.saveOrUpdate(orgSubject);
			} catch (Exception ex) {
				logger.error(ex.getMessage());
			}
		}
		setJsonString("{success:true}");
		return SUCCESS;
	}

	/**
	 * 关联下拉
	 */
	public String combo() {
		String hql = "from Subject";
		String gid  = getRequest().getParameter("gid");
		if(StringUtils.isNotBlank(gid)) {
			hql += " where grade.oid="+gid;
		}
		List<Subject> list = subjectService.findByHQL(hql);
		jsonString = new JSON2(list).with(Subject.class, "oid", "name").toJson();
		return SUCCESS;
	}

	/**
	 * 导出选中记录数
	 * */
	public String exportSel() {
		HttpServletRequest request = getRequest();
		if (ExtjsUtil.isExport(request)) {
			String sids = request.getParameter("sids");
			List<Subject> result = subjectService.getByIds(StringUtil.idStrToArr(
					sids, Long.class));
			request.setAttribute("__exportList", result);
		}

		return SUCCESS;
	}	
	
	/**
	 * 显示Opinion
	 * */
	public String showOpinion() {
		String hql = "from SubjectOpinion where subjectId=? order by checkTime asc";
		List<SubjectOpinion> opinions = subjectService.findByHQL(hql, oid);
		getRequest().setAttribute("opinions", opinions);
		
		// 是否显示操作用户（在正式分布之前，不能显示）
		Subject subject = subjectService.get(oid);
		getRequest().setAttribute("subject", subject);
		
		return "show_opinion";
	}
	
	/**
	 * 提交到待审核
	 * */
	public String checkTo2() {
		String ids = getRequest().getParameter("ids");
		String[] arr = ids.split(",");
		for(String id : arr) {
			if(StringUtils.isNotBlank(id)) {
				Subject subject = subjectService.get(Long.parseLong(id));
				subject.setStatus(2);
				subjectService.saveOrUpdate(subject);
				// 保存流转信息
				opinionService.saveOpinion(subject.getOid(), "提交到待审核", true, null);
			}
		}
		return SUCCESS;
	}
	/**
	 * 审核失败
	 * */
	public String checkTo3() {
		String ids = getRequest().getParameter("ids");
		String msg = getRequest().getParameter("msg");
		String[] arr = ids.split(",");
		for(String id : arr) {
			if(StringUtils.isNotBlank(id)) {
				Subject subject = subjectService.get(Long.parseLong(id));
				subject.setStatus(3);
				subjectService.saveOrUpdate(subject);
				// 保存流转信息
				opinionService.saveOpinion(subject.getOid(), "审核不成功", false, msg);
			}
		}
		return SUCCESS;
	}
	/**
	 * 审核成功
	 * */
	public String checkTo4() {
		String ids = getRequest().getParameter("ids");
		String[] arr = ids.split(",");
		for(String id : arr) {
			if(StringUtils.isNotBlank(id)) {
				Subject subject = subjectService.get(Long.parseLong(id));
				subject.setStatus(4);
				subjectService.saveOrUpdate(subject);
				// 保存流转信息
				opinionService.saveOpinion(subject.getOid(), "审核成功", true, null);
			}
		}
		return SUCCESS;
	}
	
	/**
	 * 选择器中的自动选中
	 * */
	public String selected() {
		String ids = getRequest().getParameter("ids");
		if(ids.startsWith(",")) {
			ids = ids.substring(1);
		}
		if(ids.endsWith(",")) {
			ids.substring(0, ids.length()-1);
		}
		String hql = "from Subject where oid in ("+ids+")";
		List<Subject> list = subjectService.findByHQL(hql);
		jsonString = Jackson.me().with(Subject.class, "oid", "name").toJson(list);
		return SUCCESS;
	}
	
	/**
	 * 保存最终分配给的那个学生
	 */
	public String saveStudent(){
		
		// 单个学生（分配给该学生）
		String userId = getRequest().getParameter("ids");
		if(StringUtils.isNotBlank(userId)) {
			Subject subject = subjectService.get(oid);
			AppUser student = appUserService2.get(Long.parseLong(userId));
			subjectService.saveStudent(student, subject);
		}
		return SUCCESS;
	}
	
	/**
	 * 列出所有没有审核教师的题目 和处于待审核状态的
	 * */
	public String listUn() {
		HttpServletRequest request = getRequest();

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);	
		filters.add(new StringPropertyFilter("NULLL_checkMember", null));
		filters.add(new StringPropertyFilter("EQI_status", "2"));

		Page<Subject> page = subjectService.search2(pageRequest, filters);

		jsonString = new JSON2(page).with(Subject.class, "oid", "name", "teacher")
					.with(AppUser.class, "fullname").toJson();
				
		return SUCCESS;
	}
	/**
	 * 列出所有没有人选的题目
	 * */
	public String listNo(){
		HttpServletRequest request = getRequest();
		
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		filters.add(new StringPropertyFilter("EQI_status", "4"));
		filters.add(new StringPropertyFilter("EQI_xscnt", "0"));

		
//		subjectService.findByHQL("from Subject where Subject", values)
		Page<Subject> page = subjectService.search2(pageRequest, filters);
		
		jsonString = new JSON2(page).with(Subject.class, "oid", "name", "teacher")
					.with(AppUser.class, "fullname").toJson();
				
		return SUCCESS;
	}
	
	
	public Long getOid() {
		return oid;
	}

	public void setOid(Long oid) {
		this.oid = oid;
	}

	public Subject getSubject() {
		return subject;
	}

	public void setSubject(Subject subject) {
		this.subject = subject;
	}

}
